<script setup lang="ts">
import RoomStatusstatus from './components//RoomStatus.vue'
import RoomAction from './components//RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import type { TimeMessages, Message } from '@/types/room'
import type { ConsultOrderItem } from '@/types/consult'
import { MsgType, OrderType } from '@/enums'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { useRoute } from 'vue-router'
import { onUnmounted, ref, onMounted, nextTick } from 'vue'
import { getConsultOrderDetail } from '@/api/consult'
const { user } = useUserStore()
const route = useRoute()
let socket: Socket
const msgList = ref<Message[]>([])
// 1.建立即时通讯连接
onMounted(() => {
  socket = io(baseURL, {
    // 建立连接前的配置
    auth: { token: `Bearer ${user?.token}` }, // 身份认证
    query: { orderId: route.query.orderId } // 订单id
  })
  // 建立连接成功,connect ：固定参数写法
  socket.on('connect', () => {
    console.log('connect')
  })
  // 错误异常消息
  socket.on('error', err => {
    console.log(err)
  })
  // 已经断开连接
  socket.on('disconnect', () => {
    console.log('disconnect')
  })
  // 第一次连接成功时获取聊天记录
  socket.on('chatMsgList', (res: { data: TimeMessages[] }) => {
    // 处理消息：分组的时间自己组织成一条通用消息，items取出来放后面
    const arr: Message[] = []
    res.data.forEach(item => {
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: { content: item.createTime }
      })
      arr.push(...item.items)
    })
    msgList.value.unshift(...arr)
  })
  // 订单状态变更的事件
  socket.on('statusChange', () => {
    getConsultOrderDetail<ConsultOrderItem>(route.query?.orderId as string).then(res => {
      consult.value = res.data
    })
  })
  // 接收
  socket.on('receiveChatMsg', (res: Message) => {
    msgList.value.push(res)
    // 滚动到最底部
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})
// 发送文字消息
// 1.子组件传值发送，socket.emit事件
// 2.发送完在接收 socket.on事件 receiveChatMsg ,然后追加到消息列表
// 3.渲染的时候区分自己的消息还是医生的
const sendText = (content: string) => {
  // 发送
  socket.emit('sendChatMsg', {
    from: user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content }
  })
}

// 接诊状态的控制：订单详情的接口（等待中，问诊中，问诊结束或者问诊取消）
// 1.组件挂载阶段获取当前接诊状态，
// 2.订单状态变更后，及时修改问诊状态
// 3.根据订单状态控制下方聊天框和图片的禁用启用以及顶部状态栏的渲染
const consult = ref<ConsultOrderItem>()
onMounted(() => {
  getConsultOrderDetail<ConsultOrderItem>(route.query?.orderId as string).then(res => {
    consult.value = res.data
  })
})
// 组件卸载关闭连接
onUnmounted(() => {
  socket.close()
})
</script>
<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <RoomStatusstatus :status="consult?.status" :countdown="consult?.countdown"></RoomStatusstatus>
    <RoomMessage :list="msgList"></RoomMessage>
    <RoomAction @send-text="sendText" :disabled="consult?.status === OrderType.ConsultChat ? false : true"></RoomAction>
  </div>
</template>
<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
